package com.mactivity.activities;

import java.util.ArrayList;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.mactivity.database.NotificationActivityFunctions;
import com.mactivity.helper.Constants;
import com.mactivity.helper.Messages;
import com.mactivity.helper.SharedPreferenceHelper;

/**
 *  @author Sanjay Vasudeva
 *  NotificationsActivity class which helps in controlling Notifications in the system and directing to screen which shows the details 
 */
public class NotificationActivity extends Activity{
	SharedPreferenceHelper preferenceHelper;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads().detectDiskWrites().detectNetwork() // or	.detectAll() for all detectable problems
		.penaltyLog().build());

		super.onCreate(savedInstanceState);
		setContentView(R.layout.notification);

		preferenceHelper =  new SharedPreferenceHelper(this);
		Map<String, String> userInfo=preferenceHelper.getUserInformation();
		ArrayAdapter<String> adapter;
		//get user id from SharedPreference
		Integer I=new Integer(Integer.parseInt(userInfo.get(Constants.USER_ID)));
		String response = null;
		NotificationActivityFunctions notificationActivityFunctions=new NotificationActivityFunctions();
		try{
			//get the notifications from database.
			response = notificationActivityFunctions.getNotifications(I);
			if(response.length()>5){
				try{
					String returnString = "";
					String noteFrom="";
					int typeStatus,noteType,groupPlanId,noteFromId,noteToId,noteId;
					ArrayList<String> listItems=new ArrayList<String>();
					JSONArray jArray = new JSONArray(response);
					final Integer note_arr_id[] = new Integer[jArray.length()]; 
					final Integer noteto_arr_id[] = new Integer[jArray.length()]; 
					final Integer notefrom_arr_id[] = new Integer[jArray.length()]; 
					final Integer gp_arr_id[] = new Integer[jArray.length()]; 
					final Integer typestatus_arr_id[] = new Integer[jArray.length()]; 
					for(int i=0;i<jArray.length();i++){
						JSONObject json_data = jArray.getJSONObject(i);
						noteFrom=json_data.getString(Constants.JSON_STRING_NAME);
						noteId=json_data.getInt(Constants.JSON_STRING_NOTEID);
						noteFromId=json_data.getInt(Constants.JSON_STRING_NOTEFROM);
						noteToId=json_data.getInt(Constants.JSON_STRING_NOTETO);
						noteType=json_data.getInt(Constants.JSON_STRING_NOTETYPE);
						typeStatus=json_data.getInt(Constants.JSON_STRING_TYPESTATUS);
						Integer N=new Integer(noteId);
						note_arr_id[i]=N;
						Integer NF=new Integer(noteFromId);
						notefrom_arr_id[i]=NF;
						Integer NT=new Integer(noteToId);
						noteto_arr_id[i]=NT;
						Integer TS=new Integer(typeStatus);
						typestatus_arr_id[i]=TS;
						Integer GP=new Integer(0);
						gp_arr_id[i]=GP;
						//Friend Request message
						if(noteType==1 && typeStatus==1){
							returnString=Messages.NOTIFICATION_FRIEND_REQUEST+noteFrom;
						}
						//Group Plan Request 
						else if(noteType==2 && typeStatus==1){
							returnString=Messages.NOTIFICATION_GROUPPLAN_REQUEST+noteFrom;
							groupPlanId=json_data.getInt(Constants.CONSTANT_EXTRAS_GROUPPLANID);
							GP=new Integer(groupPlanId);
							gp_arr_id[i]=GP;
							typestatus_arr_id[i]=TS;
						}
						//Friend Request accepted
						else if(noteType==1 && typeStatus==2){
							returnString=noteFrom+Messages.NOTIFICATION_FRIEND_ACCEPT;
						}
						//Friend Request rejected
						else if(noteType==1 && typeStatus==3){
							returnString=noteFrom+Messages.NOTIFICATION_FRIEND_REJECT;
						}
						//Group Plan accept message
						else if(noteType==2 && typeStatus==2){
							returnString=noteFrom+Messages.NOTIFICATION_GROUPPLAN_ACCEPT;
							groupPlanId=json_data.getInt(Constants.CONSTANT_EXTRAS_GROUPPLANID);
							GP=new Integer(groupPlanId);
							gp_arr_id[i]=GP;
							typestatus_arr_id[i]=TS;
						}
						//Group Plan rejected
						else if(noteType==2 && typeStatus==3){
							returnString=noteFrom+Messages.NOTIFICATION_GROUPPLAN_REJECT;
							groupPlanId=json_data.getInt(Constants.CONSTANT_EXTRAS_GROUPPLANID);
							GP=new Integer(groupPlanId);
							gp_arr_id[i]=GP;
							typestatus_arr_id[i]=TS;
						}
						listItems.add(returnString);
					}
					//set the adapter for list view
					adapter=new ArrayAdapter<String>(this,
							android.R.layout.simple_list_item_1,
							listItems);
					ListView lv1;
					final int ACTIVITY_CREATE = 0;
					lv1 = (ListView) findViewById(R.id.main_list);
					lv1.setAdapter(adapter);
					lv1.setTextFilterEnabled(true);
					//On clicking on a notification 
					lv1.setOnItemClickListener(new OnItemClickListener(){
						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							//When there is a group id set, it means its a group plan request,accept or reject
							if(gp_arr_id[arg2]>=1){
								Intent i = new Intent(NotificationActivity.this, NotificationGroupPlanActivity.class);
								i.putExtra(Constants.CONSTANT_EXTRAS_GROUPPLANID, gp_arr_id[arg2]);
								i.putExtra(Constants.CONSTANT_EXTRAS_TOID, noteto_arr_id[arg2]);
								i.putExtra(Constants.CONSTANT_EXTRAS_FROMID, notefrom_arr_id[arg2]);
								i.putExtra(Constants.COLUMN_NOTIFICATION_NOTEID, note_arr_id[arg2]);
								i.putExtra(Constants.COLUMN_NOTIFICATION_TYPESTATUS, typestatus_arr_id[arg2]);
								startActivityForResult(i, ACTIVITY_CREATE);
								NotificationActivity.this.finish();
							}
							//Friend Request
							else if(typestatus_arr_id[arg2] == 1){
								Intent i = new Intent(NotificationActivity.this, NotificationFriendActivity.class);
								i.putExtra(Constants.CONSTANT_EXTRAS_TOID, noteto_arr_id[arg2]);
								i.putExtra(Constants.CONSTANT_EXTRAS_USERID, notefrom_arr_id[arg2]);
								i.putExtra(Constants.COLUMN_NOTIFICATION_NOTEID, note_arr_id[arg2]);
								startActivityForResult(i, ACTIVITY_CREATE);
								NotificationActivity.this.finish();
							}
							//Friend request accepted or rejected
							else if(typestatus_arr_id[arg2] > 1){
								Integer I=new Integer(note_arr_id[arg2].toString());
								try {
									NotificationActivityFunctions notificationActivityFunctions=new NotificationActivityFunctions();
									//delete the notification passing the NoteId
									notificationActivityFunctions.deleteNotification(I);
									//After the notification is checked it will be deleted and show notification table back
									Intent i = new Intent(NotificationActivity.this, NotificationActivity.class);
									startActivityForResult(i, ACTIVITY_CREATE);
									NotificationActivity.this.finish();
								} catch (Exception e) {
									// TODO Auto-generated catch block
									Log.e(Constants.LOGGER_ERROR_TAG,"Exception while deleting Friend request accepted message"+ e.getMessage());
								}
							}
						}

					});
				}

				catch(JSONException e){
					Log.e("log_tag", "Error parsing data "+e.toString());
				}
			}
			else{
				TextView requestfromname = (TextView) findViewById(R.id.notificationsheader);
				requestfromname.setText("There are no notifications.");
			}
		}
		catch(Exception e){
			Log.e("log_tag","Error in http connection!!" + e.toString());					
		}
	}

	public void onClick(View v) {

	}
	@Override
	public void onBackPressed() {
		final int ACTIVITY_CREATE = 0;
		Intent i = new Intent(NotificationActivity.this, HomeActivity.class);
		startActivityForResult(i, ACTIVITY_CREATE);
		NotificationActivity.this.finish();
	}

}

